<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\MemberTask;
use App\Admin\Repositories\OrgDepartment;
use App\Admin\Repositories\OrgDepartmentOwner;
use App\Admin\Repositories\OrgTeam;
use App\Admin\Repositories\OrgTeamOwner;
use App\Admin\Repositories\TaskMemberMap;
use App\Admin\Repositories\TeamMember;
use App\Admin\Repositories\TodoTask;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Layout\Content;
use Dcat\Admin\Show;
use Dcat\Admin\Widgets\Markdown;
use Illuminate\Support\Facades\Auth;

class MemberTaskController extends AdminController
{
    protected $title = "任务管理";

    public function index(Content $content)
    {
        return $content
            ->header('任务管理')
            ->description('任务视角')
            ->body($this->grid());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new MemberTask(['member.info']), function (Grid $grid) {
            $department_id_list = $team_id_list = [];
            //角色区分数据
            if ($this->isAdmin()){
                $grid->model()
                    ->orderBy('status')
                    ->orderBy('task_id', 'desc');
            }else{
                $owner_department_list = app(OrgDepartmentOwner::class)->getDepartmentListByOwnerUid(Auth::guard('admin')->id());
                if ($owner_department_list){
                    $department_id_list = $owner_department_list->pluck('department_id')->toArray();
                }
                $owner_team_list = app(OrgTeamOwner::class)->getTeamListByOwnerUidAndDepartmentIds(Auth::guard('admin')->id(), $department_id_list);
                if ($owner_team_list){
                    $team_id_list = $owner_team_list->pluck('team_id')->unique()->toArray();
                }

                $grid->model()
                    ->whereIn('team_id', $team_id_list)
                    ->orderBy('status')
                    ->orderBy('task_id', 'desc');
            }

            $grid->column('task_id', '任务ID')->sortable();
            $grid->column('member', '执行人')->display(function($users){
                $user_str = [];
                foreach ($users as $user){
                    $user_str[] = '<span class="label" style="background:#d2d6de;color: #555">'.$user['info']['member_name'].'</span>';
                }
                return implode(' ', $user_str);
            });
            $grid->column('project_name');
            $grid->column('task_name');

            $grid->column('priority')->display(function ($item){
                return \App\Models\MemberTask::$priority_list[$item];
            })->badge(\App\Models\MemberTask::$priority_color)->sortable();

            $grid->column('progressBar', '时间进度')
                ->width(100)
                ->display(function (){
                    $start_time = strtotime($this->start_time);
                    $end_time = strtotime($this->end_time);
                    $current_time = time();
                    if (empty($start_time) || empty($end_time)){
                        return 0;
                    }
                    if ($current_time < $start_time) {
                        return 0;
                    }elseif($current_time > $end_time){
                        return 100;
                    }
                    return ceil(($current_time - $start_time)/($end_time - $start_time)*100);
                })->progressBar();

            $grid->column('progress', '进展情况')->display(function($item){
                return \App\Models\MemberTask::$progress_list[$item];
            })->dot(\App\Models\MemberTask::$progress_color)->sortable();

            $grid->column('status', '任务状态')
                ->select(\App\Models\MemberTask::$status_list)
                ->sortable();

            $grid->column('start_time')->sortable();
            $grid->column('end_time')->sortable();

            $grid->filter(function (Grid\Filter $filter) use ($team_id_list) {
                $filter->panel();
                if ($this->isAdmin()){
                    $department_list = app(OrgDepartment::class)->getOptionList();
                }else{
                    $owner_team_list = app(OrgTeamOwner::class)->getTeamListByOwnerUid(Auth::guard('admin')->id());
                    $department_id_list = $owner_team_list->pluck('department_id')->unique()->toArray();
                    $department_list = app(OrgDepartment::class)->getOptionListByDepartmentIds($department_id_list);
                }

                $filter->equal('department_id', '部门')
                    ->width(2)
                    ->select($department_list)
                    ->load('team_id', '/api/team');
                $filter->equal('team_id', '小组')
                    ->width(2)
                    ->select();

                $filter->in('priority')->multipleSelect(\App\Models\MemberTask::$priority_list)->width(3);
                $filter->in('status', '任务状态')->multipleSelect(\App\Models\MemberTask::$status_list)->width(3);
                $filter->between('start_time', '开始时间')->datetime()->width(4);
                $filter->between('end_time', '结束时间')->datetime()->width(4);
                $filter->equal('progress', '进展情况')->radio(\App\Models\MemberTask::$progress_list)->width(3);
            });

            $grid->disableRowSelector();
            $grid->setActionClass(Grid\Displayers\Actions::class);
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new MemberTask(['member.info']), function (Show $show) use ($id) {
            $task_info = app(MemberTask::class)->getById($id);
            $show->task_id;
            $show->field('department_name', '所属部门')->as(function() use ($task_info){
                $department_info = app(OrgDepartment::class)->getById($task_info['department_id']);
                return $department_info['name'];
            });
            $show->field('team_name', '所属小组')->as(function() use ($task_info){
                $team_info = app(OrgTeam::class)->getById($task_info['team_id']);
                return $team_info['name'];
            });
            $show->field('member', '执行人')->as(function() use ($id){
                $member_id_list = app(TaskMemberMap::class)->getMemberIdListByTaskId($id)->pluck('member_id')->toArray();
                $member_list = app(TeamMember::class)->getMemberListByMemberIds($member_id_list)->pluck('member_name')->toArray();
                return $member_list;
            })->label();
            $show->field('project_name');
            $show->task_name;
            $show->start_time;
            $show->end_time;
            $show->field('priority')->using(
                \App\Models\MemberTask::$priority_list
            )->badge(\App\Models\MemberTask::$priority_color[$task_info['priority']]);

            $show->html(function() use ($task_info){
                $start_time = strtotime($task_info['start_time']);
                $end_time = strtotime($task_info['end_time']);
                $current_time = time();
                if (empty($start_time) || empty($end_time)){
                    $rate = 0;
                }else{
                    if ($current_time < $start_time) {
                        $rate = 0;
                    }elseif($current_time > $end_time){
                        $rate = 100;
                    }else{
                        $rate = ceil(($current_time - $start_time)/($end_time - $start_time)*100);
                    }
                }

                $header = '<div class="show-field form-group row"><div class="col-sm-2 control-label"><span>任务进度</span></span></div><div class="col-sm-8"><div class="box box-solid box-default no-margin box-show"><div class="box-body">';
                $content = <<<HTML
<div class="shadow-100 progress progress-bar-primary">
    <div class="progress-bar" role="progressbar" aria-valuenow="1" aria-valuemin="0" aria-valuemax="100" style="width:{$rate}%"></div>
</div>
HTML;
                $footer = '</div></div></div></div>';
                return $header.$content.$footer;
            });

            $show->field('progress', '进展情况')->using(
                \App\Models\MemberTask::$progress_list
            )->dot(\App\Models\MemberTask::$progress_color);

            $show->field('status', '任务状态')->using(\App\Models\MemberTask::$status_list);

            $show->html(function (){
                $header = '<div class="show-field form-group row"><div class="col-sm-2 control-label"><span>任务描述</span></span></div><div class="col-sm-8"><div class="box box-solid box-default no-margin box-show"><div class="box-body" style="max-height:500px;overflow:auto"> ';
                $content = Markdown::make($this->task_desc);
                $footer = '</div></div></div></div>';
                return $header.$content.$footer;
            });
            $show->field('completed_at', '任务完成时间');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    protected function form()
    {
        $todo_id = request('todo_id');
        $todo_info = null;

        if ($todo_id){
            $todo_info = app(TodoTask::class)->getById($todo_id);
        }

        return Form::make(new MemberTask(['member']), function (Form $form) use ($todo_info) {

            if ($this->isAdmin()){
                $department_list = app(OrgDepartment::class)->getOptionList();
            }else{
                $owner_team_list = app(OrgTeamOwner::class)->getTeamListByOwnerUid(Auth::guard('admin')->id());
                $department_id_list = $owner_team_list->pluck('department_id')->unique()->toArray();
                $department_list = app(OrgDepartment::class)->getOptionListByDepartmentIds($department_id_list);
            }

            if ($form->isEditing()) {
                $form->select('department_id', '所属部门')
                    ->options($department_list)
                    ->load('team_id', '/api/team')
                    ->required();
                $form->select('team_id', '选择小组')
                    ->load('member_id', '/api/member')
                    ->required();
                $edit_member_list = app(TaskMemberMap::class)->getMemberIdListByTaskId($form->getKey());
                $form->multipleSelect('member_id', '选择任务执行人')
                    ->default(collect($edit_member_list)->pluck('member_id')->toArray(), true)
                    ->required();
            }else{
                $form->select('department_id', '所属部门')
                    ->options($department_list)
                    ->load('team_id', '/api/team')
                    ->required();
                $form->select('team_id', '选择小组')
                    ->load('member_id', '/api/member')
                    ->required();
                $form->multipleSelect('member_id', '选择任务执行人')->required();
            }

            $form->text('project_name')
                ->maxLength(15, '最长不超过15个字符')
                ->required();

            if ($todo_info){
                $form->text('task_name')
                    ->maxLength(30, '最长不超过30个字符')
                    ->value($todo_info['task_name'])
                    ->required();
                $form->markdown('task_desc')
                    ->options([
                        'mode' => 'markdown',
                        'imageUpload' => false,
                    ])->value($todo_info['task_desc']);
                $form->hidden('todo_id')->value($todo_info['todo_id']);
            }else{
                $form->text('task_name')
                    ->maxLength(30, '最长不超过30个字符')
                    ->required();
                $form->markdown('task_desc')
                    ->options([
                        'mode' => 'markdown',
                        'imageUpload' => false,
                    ]);
            }

//            $form->markdown('task_desc')->imageDirectory('/markdown/images');

            $form->select('status', '任务状态')
                ->options(\App\Models\MemberTask::$status_list)
                ->default(\App\Models\MemberTask::TASK_STATUS_ING)
                ->required()
                ->width(3);
            $form->datetimeRange('start_time', 'end_time', '任务开始结束时间')
                ->attribute(['style' => 'z-index:999999999'])->required();
            $form->radio('priority')->options(\App\Models\MemberTask::$priority_list)->default(\App\Models\MemberTask::TASK_PRIORITY_MEDIUM)->required();

            $form->saving(function (Form $form){
                if (!empty($form->task_desc) && count($form->task_desc) > 1500){
                    $form->responseValidationMessages('task_desc', '最长不超过1500个字符');
                }
            });

            $form->footer(function ($footer) {
                // 去掉`重置`按钮
//                $footer->disableReset();
                // 去掉`查看`checkbox
                $footer->disableViewCheck();
                // 去掉`继续编辑`checkbox
                $footer->disableEditingCheck();
                // 去掉`继续创建`checkbox
                $footer->disableCreatingCheck();
            });
        });
    }

    public function update($id)
    {
        if(count(request()->all()) > 2){
            $department_id = request('department_id');
            $department_info = app(MemberTask::class)->getById($department_id);
            $team_id = request('team_id');
            $task_name = request('task_name');
            $project_name = request('project_name');
            $member_id_list = request('member_id');
            $task_desc = request('task_desc');
            $start_time = request('start_time');
            $end_time = request('end_time');
            $priority = request('priority');
            $status = request('status', \App\Models\MemberTask::TASK_STATUS_ING);

            $end_timestamp = strtotime($end_time);
            $current_timestamp = time();

            $progress = \App\Models\MemberTask::TASK_PROGRESS_NORMAL;
            if ($status == \App\Models\MemberTask::TASK_STATUS_ING){
                if($current_timestamp > $end_timestamp){
                    $progress = \App\Models\MemberTask::TASK_PROGRESS_DELAY;
                }
            }
            $completed_at = $department_info['completed_at'] ?? null;
            if ($status == \App\Models\MemberTask::TASK_STATUS_COMPLETE && $department_info['status'] != \App\Models\MemberTask::TASK_STATUS_COMPLETE){
                $completed_at = date('Y-m-d H:i:s');
            }

            if (app(MemberTask::class)->updt($id, $department_id, $team_id, $task_name, $project_name, $start_time, $end_time, $priority, $member_id_list, $task_desc, $status, $progress, $completed_at)){
                return response()->json([
                    'message' => '编辑成功',
                    'status' => true,
                    'redirect' => admin_url('/task/mng')
                ]);
            }
            return response()->json([
                'message' => '编辑失败',
                'status' => false,
                'redirect' => ''
            ]);
        }else{
            $status = request('status', \App\Models\MemberTask::TASK_STATUS_ING);
            $data = [
                'status' => $status,
                'completed_at' => null,
            ];
            if ($status == \App\Models\MemberTask::TASK_STATUS_COMPLETE){
                $data['completed_at'] = date('Y-m-d H:i:s');
            }
            if (app(MemberTask::class)->updateFields($id, $data)){
                return response()->json([
                    'message' => '更新成功',
                    'status' => true,
                    'redirect' => ''
                ]);
            }
            return response()->json([
                'message' => '更新失败',
                'status' => false,
                'redirect' => ''
            ]);
        }
    }

    public function store()
    {
        $department_id = request('department_id');
        $team_id = request('team_id');
        $task_name = request('task_name');
        $project_name = request('project_name');
        $member_id_list = request('member_id');
        $task_desc = request('task_desc');
        $start_time = request('start_time');
        $end_time = request('end_time');
        $priority = request('priority');
        $status = request('status', \App\Models\MemberTask::TASK_STATUS_ING);
        $todo_id = request('todo_id');

        $end_timestamp = strtotime($end_time);
        $current_timestamp = time();

        $progress = \App\Models\MemberTask::TASK_PROGRESS_NORMAL;
        if ($status == \App\Models\MemberTask::TASK_STATUS_ING){
            if($current_timestamp > $end_timestamp){
                $progress = \App\Models\MemberTask::TASK_PROGRESS_DELAY;
            }
        }
        $completed_at = null;
        if ($status == \App\Models\MemberTask::TASK_STATUS_COMPLETE){
            $completed_at = date('Y-m-d H:i:s');
        }

        if ($task_id = app(MemberTask::class)->add($department_id, $team_id, $task_name, $project_name, $start_time, $end_time, $priority, $member_id_list, $task_desc, $status, $progress, $completed_at)){
            if ($todo_id){
                app(TodoTask::class)->upd($todo_id, [
                    'task_id' => $task_id,
                    'status' => \App\Models\TodoTask::TODO_STATUS_DSTRBT
                ]);
            }
            return response()->json([
                'message' => '添加成功',
                'status' => true,
                'redirect' => admin_url('/task/mng')
            ]);
        }
        return response()->json([
            'message' => '添加失败',
            'status' => false,
            'redirect' => ''
        ]);
    }

    public function destroy($id)
    {
        if (app(MemberTask::class)->del($id)){
            return response()->json([
                'message' => '删除成功',
                'status' => true,
                'redirect' => ''
            ]);
        }
        return response()->json([
            'message' => '删除失败',
            'status' => false,
            'redirect' => ''
        ]);
    }

    public function api()
    {
        $team_id = request('q');
        return app(TeamMember::class)->getOptionsByTeamId($team_id);
    }
}
